package io.renren.modules.demo.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.dto.CategoryDTO;
import io.renren.common.dto.DishDTO;
import io.renren.common.dto.SetmealDTO;
import io.renren.common.entity.DishFlavorEntity;
import io.renren.common.entity.SetmealDishEntity;
import io.renren.common.page.PageData;
import io.renren.common.redis.RedisKeys;
import io.renren.common.redis.RedisUtils;
import io.renren.common.service.CategoryService;
import io.renren.common.service.SetmealDishService;
import io.renren.common.service.SetmealService;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;

import io.renren.modules.demo.excel.SetmealExcel;

import io.renren.modules.oss.service.SysOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 套餐
 *
 * @author yidian ${email}
 * @since 1.0.0 2022-11-06
 */
@RestController
@RequestMapping("demo/setmeal")
@Api(tags="套餐")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SysOssService sysOssService;

    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("demo:setmeal:page")
    @Transactional(rollbackFor = Exception.class)
    @Cacheable(value = "setmealPageCache",key = "'setmeal_'+#params.get('limit')+'_'+#params.get('page')")
    public Result<PageData<SetmealDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<SetmealDTO> page = setmealService.page(params);


        List<SetmealDTO> list = page.getList();
        List<SetmealDTO> dtoList = list.stream().map(item -> {
            // 获取categoryId
            Long categoryId = item.getCategoryId();
            getByWithCategory(item,categoryId);
            // 当前套餐ID
            Long setmealId = item.getId();
            setmealService.getByWithSetmealDish(item,setmealId);
            return item;
        }).collect(Collectors.toList());
        page.setList(dtoList);
        

        return new Result<PageData<SetmealDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("demo:setmeal:info")
    @Cacheable(value = "setmealCache",key = "'setmeal_'+#id")
    @Transactional(rollbackFor = Exception.class)
    public Result<SetmealDTO> get(@PathVariable("id") Long id){
        SetmealDTO dto = setmealService.get(id);
        getByWithCategory(dto,dto.getCategoryId());
        setmealService.getByWithSetmealDish(dto,id);
        return new Result<SetmealDTO>().ok(dto);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("demo:setmeal:save")
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict = {
            @CacheEvict(value = "setmealDishPageCache",allEntries = true),
            @CacheEvict(value = "setmealPageCache",allEntries = true)
    })
    public Result save(@RequestBody SetmealDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        setmealService.save(dto);
        System.out.println(dto.getId());
        List<SetmealDishEntity> setmealDishes = dto.getSetmealDishes();
        setmealDishes.stream().map(item -> {
            Long id = dto.getId();
            item.setSetmealId(String.valueOf(id));
            setmealDishService.insert(item);
            return item;
        }).collect(Collectors.toList());

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("demo:setmeal:update")
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict = {
            @CacheEvict(value = "setmealCache",key = "'setmeal_'+#dto.getId()"),
            @CacheEvict(value = "setmealPageCache",allEntries = true),
            @CacheEvict(value = "setmealDishPageCache",allEntries = true),
    })
    public Result update(@RequestBody SetmealDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        //更新前删除表中之前存储的图片数据（判断图片是否更改）
        SetmealDTO setmealDTO = setmealService.get(dto.getId());
        if (setmealDTO.getImage()!=dto.getImage()){
            sysOssService.deleteByKey(setmealDTO.getImage());
        }
        
        List<SetmealDishEntity> setmealDishes = dto.getSetmealDishes();
        setmealDishes.stream().map(item -> {
            String id = String.valueOf(dto.getId());
            if (item.getSetmealId()==null){
                item.setSetmealId(id);
            }
            if (item.getId()==null){
                setmealDishService.insert(item);
            }else {
                setmealDishService.updateById(item);
            }
            return item;
        }).collect(Collectors.toList());

        setmealService.update(dto);

        return new Result();
    }


    @PutMapping("/updateStatus/{status}")
    @ApiOperation("修改状态")
    @LogOperation("修改状态")
    @RequiresPermissions("demo:setmeal:update")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "setmealPageCache",allEntries = true)
    public Result updateStatus(@PathVariable("status") Integer status, @RequestBody Long[] id){
        //效验数据
        AssertUtils.isArrayEmpty(id, "id");
        for (Long aLong : id) {
            redisUtils.delete(RedisKeys.getSetmealCacheKey()+"::setmeal_"+aLong);
            SetmealDTO setmealDTO = setmealService.get(aLong);
            setmealDTO.setStatus(status);
            setmealService.update(setmealDTO);
        }
        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("demo:setmeal:delete")
    @Caching(evict = {
            @CacheEvict(value = "setmealDishPageCache",allEntries = true),
            @CacheEvict(value = "setmealPageCache",allEntries = true)
    })
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        setmealDishService.deleteBySetmealId(ids);

        //同步删除云存储图片
        for (Long id : ids) {
            SetmealDTO setmealDTO = setmealService.get(id);
            sysOssService.deleteByKey(setmealDTO.getImage());
            redisUtils.delete(RedisKeys.getSetmealCacheKey()+"::setmeal_"+id);
        }
        setmealService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("demo:setmeal:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SetmealDTO> list = setmealService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, SetmealExcel.class);
    }

    /**
     * 提取方法setmeal获得分类信息
     * @param setmealDTO
     * @param categoryId
     */
    public void getByWithCategory(SetmealDTO setmealDTO, Long categoryId) {
        // 给categoryName赋值
        CategoryDTO categoryDTO = categoryService.get(categoryId);
        if(categoryDTO!=null){
            String name = categoryDTO.getName();
            setmealDTO.setCategoryName(name);
        }
    }

}